<template>
  <div class="container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>{{ $t("common.loading") }}</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <i class="error-icon"></i>
      <!-- <p>{{ $t("common.loadFailed") }}</p> -->
      <button @click="refreshData" class="refresh-btn">
        {{ $t("common.refresh") }}
      </button>
    </div>

    <!-- 主内容区 -->
    <div v-else>
      <!-- 市场概览卡片 -->
      <section class="stats-cards">
        <div class="stats-card">
          <div class="card-meta">{{ $t("market.totalMarketCap") }}</div>
          <span v-if="getCurrency === 'cny'" class="card-value">
            ¥
            <span class="highlight">{{
              marketData.total_market_cap?.cny | wyi | numberFormat
            }}</span>
            万亿</span
          >
          <span v-if="getCurrency === 'usd'" class="card-value">
            $
            <span class="highlight">{{
              marketData.total_market_cap?.usd | wyi | numberFormat
            }}</span>
            万亿</span
          >
        </div>
        <!-- <div class="stats-card" :class="{ up: marketData.market_cap_change_percentage_7d_usd > 0, down: marketData.market_cap_change_percentage_7d_usd < 0 }">
          <div class="card-meta">{{ $t('market.marketCapChange7d') }}</div>
          <div class="card-value">
            <span class="change-percent"> + <span class="highlight change-percent">{{ marketData.market_cap_change_percentage_7d_usd | numberFormat(2)}}</span> %</span>
            <small>¥{{ marketData.market_cap_change_7d?.cny| yi | numberFormat }}</small>
          </div>
        </div> -->
        <div class="stats-card">
          <div class="card-meta">{{ $t("market.volume24h") }}</div>
          <span  class="card-value">
            {{ getCurrency === 'cny'? '¥': '$' }}
            <span class="highlight">{{
              marketData.total_volume?.[getCurrency] | wyi | numberFormat
            }}</span>
            万亿</span
          >
          <!-- <span v-if="getCurrency === 'usd'" class="card-value">
            $
            <span class="highlight">{{
              marketData.total_volume?.usd | wyi | numberFormat
            }}</span>
            万亿</span
          > -->
        </div>
        <div class="stats-card">
          <div class="card-meta">{{ $t("market.activeCryptocurrencies") }}</div>
          <div class="card-value">
            <span>
              {{ marketData.active_cryptocurrencies }}
            </span>
          </div>
        </div>
      </section>

      <!-- 币种列表 -->
      <section class="coins-table-container">
        <table class="market-table">
          <thead>
            <tr>
              <th>{{ $t("market.rank") }}</th>
              <th>{{ $t("market.coin") }}</th>
              <th @click="sortByColumn('market_cap')" class="sortable-header">
                {{ $t("market.marketCap")
                }}{{ getCurrency === "cny" ? "(¥)" : "($)" }}
                <span
                  class="sort-indicator"
                  :class="getSortIndicator('market_cap')"
                ></span>
              </th>
              <th
                @click="sortByColumn('current_price')"
                class="sortable-header"
              >
                {{ $t("market.price")
                }}{{ getCurrency === "cny" ? "(¥)" : "($)" }}
                <span
                  class="sort-indicator"
                  :class="getSortIndicator('current_price')"
                ></span>
              </th>
              <th @click="sortByColumn('total_volume')" class="sortable-header">
                {{ $t("market.volume")
                }}{{ getCurrency === "cny" ? "(¥)" : "($)" }}
                <span
                  class="sort-indicator"
                  :class="getSortIndicator('total_volume')"
                ></span>
              </th>
              <th
                @click="sortByColumn('circulating_supply')"
                class="sortable-header"
              >
                {{ $t("market.circulatingSupply") }}
                <span
                  class="sort-indicator"
                  :class="getSortIndicator('circulating_supply')"
                ></span>
              </th>
              <th
                @click="sortByColumn('turnover_rate')"
                class="sortable-header"
              >
                {{ $t("market.turnoverRate") }}
                <span
                  class="sort-indicator"
                  :class="getSortIndicator('turnover_rate')"
                ></span>
              </th>
              <th
                @click="sortByColumn('price_change_percentage_24h')"
                class="sortable-header"
              >
                {{ $t("market.change24h") }}
                <span
                  class="sort-indicator"
                  :class="getSortIndicator('price_change_percentage_24h')"
                ></span>
              </th>
              <th>{{ $t("market.trend7d") }}</th>
            </tr>
          </thead>
          <tbody
            ref="tableBody"
            @scroll="handleTbodyScroll"
            class="scrollable-tbody"
          >
            <div v-if="listLoading" class="loading-container">
              <div class="loading-spinner"></div>
              <p>{{ $t("common.loading") }}</p>
            </div>
            <tr
              v-for="(coin, index) in filteredCoins"
              :key="coin.id"
              :class="{ odd: index % 2 }"
              class="coin-row"
              @click="goToDetail(coin, coin.id)"
            >
              <td>{{ index + 1 }}</td>
              <td class="coin-info">
                <img :src="coin.image" :alt="coin.name" class="coin-logo" />
                <div class="coin-details">
                  <span class="coin-name">{{ coin.name }}</span>
                  <span class="coin-symbol">{{
                    coin.symbol.toUpperCase()
                  }}</span>
                </div>
              </td>
              <td>{{ (coin.market_cap / 100000000).toFixed(2) }} 亿</td>
              <td>{{ coin.current_price | numberFormat(2) }}</td>
              <td>{{ (coin.total_volume / 100000000).toFixed(2) }} 亿</td>
              <td>{{ (coin.circulating_supply / 10000).toFixed(2) }} 万</td>
              <td>
                {{
                  (coin.turnover_rate = (
                    (coin.total_volume / coin.market_cap) *
                    100
                  ).toFixed(2))
                }}%
              </td>
              <td
                :class="{
                  up: coin.price_change_percentage_24h > 0,
                  down: coin.price_change_percentage_24h < 0,
                }"
              >
                {{ coin.price_change_percentage_24h | numberFormat(2) }}%
              </td>
              <td class="trend-column">
                <TrendLine :data="coin.sparkline_in_7d?.price || []" />
              </td>
            </tr>
          </tbody>
        </table>
      </section>
      <!-- 加载更多状态 -->
      <div v-if="loadingMore" class="loading-more">
        <div class="loading-spinner"></div>
        <p>{{ $t("common.loadingMore") }}</p>
      </div>
      <!-- 加载更多按钮 -->
      <!-- <button 
        v-else-if="hasMoreData && trendingCoins.length > 0" 
        @click="loadMore" 
        class="load-more-btn"
      >
        {{ $t('common.loadMore') }}
      </button> -->

      <div v-if="!hasMoreData && trendingCoins.length > 0" class="no-more-data">
        {{ $t("common.noMoreData") }}
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import TrendLine from "@/components/TrendLine.vue";
import { mapGetters } from "vuex";

export default {
  components: { TrendLine },
  data() {
    return {
      marketData: {},
      trendingCoins: [],
      filteredCoins: [],
      loading: true,
      listLoading: false,
      error: false,
      searchQuery: "",
      sortConfig: {
        column: "market_cap", // 默认按市值排序
        direction: "desc", // 默认降序
      },
      lastUpdated: "",
      lastUpdated: "",
      currentPage: 1, // 当前页码
      perPage: 20, // 每页数量
      hasMoreData: true, // 是否还有更多数据
      loadingMore: false, // 是否正在加载更多
    };
  },
  computed: {
    ...mapGetters(["getCurrency"]),
  },
  filters: {
    wyi(value) {
      return value / (100000000 * 10000);
    },
    yi(value) {
      return value / 100000000;
    },
    numberFormat(value, decimals = 2) {
      if (isNaN(value) || value === null || value === undefined) return "0";
      return value.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
  },
  mounted() {
    this.fetchData();
    this.$eventBus.$on("topSearchInput", this.topSearch);
  },
  watch: {
    getCurrency() {
      this.currentPage = 1;
      this.fetchData();
    },
  },
  destroyed() {
    this.$eventBus.$off("topSearchInput");
  },
  methods: {
    // 添加跳转详情页的方法
    goToDetail(coin, id) {
      this.$router.push({
        name: "CryptoDetail",
        query: { coin: JSON.stringify(coin) },
        // 携带id参数
        params: { id }, // 携带id参数
        success: () => {},
      });
      this.$eventBus.$emit("onNavigate", "CryptoDetail");
    },
    async fetchData(isLoadMore = false) {
      if (isLoadMore) {
        this.loadingMore = true;
      } else {
        this.loading = true;
      }
      this.error = false;

      const header = {
        headers: {
          vs_currency: this.getCurrency,
        },
      };

      try {
        // 并行请求数据 - 全局数据只在首次加载时获取
        let globalRes = null;
        const requests = [];

        if (!isLoadMore) {
          requests.push(
            axios.get("http://47.83.150.5:2027/api/v1/coins/global", {
              ...header,
            })
          );
        }

        // 市场数据请求（带分页参数）
        requests.push(
          axios.get(
            `http://47.83.150.5:2027/api/v1/coins/market_data?vs_currency=usd&order=gecko_desc&per_page=${this.perPage}&page=${this.currentPage}&sparkline=true&symbols=${this.searchQuery}`,
            { ...header }
          )
        );

        const responses = await Promise.all(requests);

        // 处理全局数据（仅首次加载）
        if (!isLoadMore && responses.length > 1) {
          globalRes = responses[0];
          this.marketData = globalRes.data?.data?.data ?? [];
        }

        // 处理市场数据
        const marketsRes = isLoadMore
          ? responses[0]
          : responses[responses.length - 1];
        const newCoins = marketsRes.data?.data ?? [];

        // 如果是加载更多则追加数据，否则替换数据
        this.trendingCoins = isLoadMore
          ? [...this.trendingCoins, ...newCoins]
          : newCoins;

        localStorage.setItem(
          "trendingCoins",
          JSON.stringify(this.trendingCoins)
        );

        // 检查是否还有更多数据
        this.hasMoreData = newCoins.length === this.perPage;

        this.filterCoins(); // 应用筛选和排序

        // 更新时间
        this.lastUpdated = new Date().toLocaleString();

        // 更新加载状态
        if (isLoadMore) {
          this.loadingMore = false;
        } else {
          this.loading = false;
        }
      } catch (error) {
        console.error("数据加载失败:", error);
        if (isLoadMore) {
          this.loadingMore = false;
        } else {
          this.loading = false;
        }
        this.error = true;
      }
    },
    //type 1-加载更多 2-搜索
    async loadListData(type = 1) {
      if (type === 1) {
        this.loadingMore = true;
      } else {
        this.listLoading = true;
      }
      this.error = false;

      const header = {
        headers: {
          vs_currency: this.getCurrency,
        },
      };

      try {
        // 并行请求数据 - 全局数据只在首次加载时获取
        let globalRes = null;
        const requests = [];

        // 市场数据请求（带分页参数）
        requests.push(
          axios.get(
            `http://47.83.150.5:2027/api/v1/coins/market_data?vs_currency=usd&order=gecko_desc&per_page=${this.perPage}&page=${this.currentPage}&sparkline=true&symbols=${this.searchQuery}`,
            { ...header }
          )
        );

        const responses = await Promise.all(requests);

        // 处理市场数据
        const marketsRes = responses[0];
        const newCoins = marketsRes.data?.data ?? [];

        // 如果是加载更多则追加数据，否则替换数据
        this.trendingCoins =
          type === 1 ? [...this.trendingCoins, ...newCoins] : newCoins;

        localStorage.setItem(
          "trendingCoins",
          JSON.stringify(this.trendingCoins)
        );

        // 检查是否还有更多数据
        this.hasMoreData = newCoins.length === this.perPage;

        this.filterCoins(); // 应用筛选和排序

        // 更新时间
        this.lastUpdated = new Date().toLocaleString();

        if (type === 1) {
          this.loadingMore = false;
        } else {
          this.listLoading = false;
        }
      } catch (error) {
        console.error("数据加载失败:", error);
        if (type === 1) {
          this.loadingMore = false;
        } else {
          this.listLoading = false;
        }
        this.error = true;
      }
    },
    topSearch(coinName) {
      console.log("🚀 ~ topSearch ~ topSearch:", coinName);
      this.searchQuery = coinName;
      // 搜索时重置分页并清空当前展示列表
      this.currentPage = 1;
      this.trendingCoins = [];
      this.filteredCoins = [];
      this.hasMoreData = true;
      this.listLoading = true;
      this.loadListData(2).then(() => {
        this.filterCoins();
        this.listLoading = false;
      });
    },
    filterCoins() {
      let filtered = [...this.trendingCoins];

      // 应用搜索筛选
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        filtered = filtered.filter(
          (coin) =>
            coin.name.toLowerCase().includes(query) ||
            coin.symbol.toLowerCase().includes(query)
        );
      }

      // 应用排序
      this.filteredCoins = this.sortCoins(filtered);
    },

    sortByColumn(column) {
      // 如果点击的是当前排序的列，则切换排序方向
      if (this.sortConfig.column === column) {
        this.sortConfig.direction =
          this.sortConfig.direction === "asc" ? "desc" : "asc";
      } else {
        // 否则设置新的排序列，默认降序
        this.sortConfig = {
          column,
          direction: "desc",
        };
      }

      // 重新排序
      this.filteredCoins = this.sortCoins(this.filteredCoins);
    },

    sortCoins(coins) {
      return [...coins].sort((a, b) => {
        // 处理换手率的特殊情况，因为它是计算出来的
        let valueA, valueB;
        if (this.sortConfig.column === "turnover_rate") {
          valueA = (a.total_volume / a.market_cap) * 100;
          valueB = (b.total_volume / b.market_cap) * 100;
        } else {
          valueA = a[this.sortConfig.column];
          valueB = b[this.sortConfig.column];
        }

        // 处理可能的 null/undefined 值
        if (valueA === null || valueA === undefined) return 1;
        if (valueB === null || valueB === undefined) return -1;

        // 数值比较
        if (valueA < valueB)
          return this.sortConfig.direction === "asc" ? -1 : 1;
        if (valueA > valueB)
          return this.sortConfig.direction === "asc" ? 1 : -1;
        return 0;
      });
    },

    getSortIndicator(column) {
      if (this.sortConfig.column !== column) {
        return "sort-indicator--none";
      }
      return this.sortConfig.direction === "asc"
        ? "sort-indicator--asc"
        : "sort-indicator--desc";
    },

    refreshData() {
      this.fetchData();
    },
    // 处理货币变化
    handleCurrencyChange() {
      this.currentPage = 1; // 货币变化时重置分页
      this.fetchData();
    },

    // // 处理滚动事件，实现下拉加载更多
    // handleScroll() {
    //   // 避免在加载中或没有更多数据时触发
    //   if (this.loadingMore || !this.hasMoreData || this.loading) return

    //   // 计算滚动位置
    //   const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    //   const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
    //   const clientHeight = document.documentElement.clientHeight || window.innerHeight

    //   // 当滚动到距离底部200px时加载更多
    //   if (scrollTop + clientHeight >= scrollHeight - 200) {
    //     this.loadMore()
    //   }
    // },
    // 替换原handleScroll为tbody滚动处理
    handleTbodyScroll() {
      // 避免在加载中或没有更多数据时触发
      if (this.loadingMore || !this.hasMoreData || this.loading) return;

      const tbody = this.$refs.tableBody;
      if (!tbody) return;

      // 计算tbody滚动位置
      const { scrollTop, scrollHeight, clientHeight } = tbody;

      // 当滚动到距离底部30px时加载更多
      if (scrollHeight - scrollTop - clientHeight <= 30) {
        this.loadMore();
      }
    },

    // 加载更多数据
    loadMore() {
      this.currentPage++;
      this.loadListData();
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  max-width: 100%;
  // margin: 0 auto;
  font-family: "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  color: #1e293b;
}

.page-header {
  margin-bottom: 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.page-header h1 {
  font-size: 28px;
  font-weight: 700;
  color: #0f172a;
  margin: 0;
}

.update-time {
  color: #64748b;
  font-size: 14px;
  margin: 0;
}

/* 加载状态 */
.loading-container {
  text-align: center;
  padding: 80px 0;
  width: 100%;
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 5px solid #e2e8f0;
  border-top: 5px solid #f4974c;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 15px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 错误状态 */
.error-container {
  text-align: center;
  padding: 60px 0;
  color: #dc2626;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 15px;
  display: inline-block;
  width: 48px;
  height: 48px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23dc2626'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
}

.refresh-btn {
  background-color: #3b82f6;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
  margin-top: 10px;
}

.refresh-btn:hover {
  background-color: #2563eb;
}

/* 市场概览卡片 */
.stats-cards {
  display: flex;
  gap: 39px;
  margin-bottom: 30px;
}

.stats-card {
  background: white;
  border-radius: 12px;
  width: 388px;
  height: 146px;
  background: #ffffff;
  box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.05);
  border-radius: 22px;
  padding: 34px 32px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* .stats-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background-color: #94a3b8;
} */

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1),
    0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.stats-card.up::before {
  background-color: #10b981;
}

.stats-card.down::before {
  background-color: #ef4444;
}

.card-meta {
  font-size: 18px;
  color: #302d2c;
  // margin-bottom: 10px;
  font-weight: 400;
}

.card-value {
  font-size: 16px;
  color: #302d2c;
  line-height: 1.3;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  display: flex;
  // font-weight: 400;
  align-items: baseline;
  color: #302d2c;
  span {
    font-weight: 700;
    font-size: 36px;
    color: #302d2c;
    margin: 0 6px;
  }
  .change-percent {
    color: #17a478;
  }
}

.card-value small {
  font-size: 16px;
  color: #302d2c;
  font-weight: 500;
  display: block;
  margin-top: 5px;
}

/* 筛选区域 */
.filters {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-box {
  position: relative;
  flex: 1;
  max-width: 400px;
}

.search-box input {
  width: 100%;
  padding: 10px 15px 10px 40px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.search-box input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.search-icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #94a3b8;
  width: 16px;
  height: 16px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2394a3b8'%3E%3Cpath d='M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
}

/* 排序相关样式 - 调整为更大的按钮 */
.sortable-header {
  cursor: pointer;
  position: relative;
  padding-right: 32px; /* 增加右侧 padding 以容纳更大的图标 */
  padding-top: 6px;
  padding-bottom: 6px;
}

.sort-indicator {
  position: absolute;
  right: -6px;
  top: 50%;
  transform: translateY(-50%);
  width: 16px; /* 增大图标宽度 */
  height: 16px; /* 增大图标高度 */
  display: inline-block;
  transition: all 0.2s ease;
}

.sort-indicator--none {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2394a3b8'%3E%3Cpath d='M7 10l5 5 5-5H7zm0 4h10v2H7z'/%3E%3C/svg%3E");
  opacity: 0.5;
}

.sort-indicator--asc {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%233b82f6'%3E%3Cpath d='M12 5V19l7-7-7-7z'/%3E%3C/svg%3E");
}

.sort-indicator--desc {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%233b82f6'%3E%3Cpath d='M12 19V5l-7 7 7 7z'/%3E%3C/svg%3E");
}

.sortable-header:hover {
  background-color: rgba(0, 0, 0, 0.02);
}

.sortable-header:hover .sort-indicator--none {
  opacity: 1;
  transform: translateY(-50%) scale(1.1); /* 悬停时略微放大 */
}

/* 币种表格 */
.coins-table-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05),
    0 2px 4px -1px rgba(0, 0, 0, 0.03);
  overflow: hidden;
}

.market-table {
  width: 100%;
  // border-collapse: collapse;
  border-collapse: separate; /* 改为separate避免边框合并问题 */
}

.market-table thead {
  background-color: #f1f5f9;
  position: sticky;
  top: 0;
  z-index: 1;
  background-color: #f1f5f9;
}

.market-table tbody {
  display: block; /* 改为块级元素才能设置高度 */
  height: 700px; /* 固定高度 */
  overflow-y: auto; /* 垂直方向超出滚动 */
  overflow-x: hidden; /* 隐藏水平滚动 */
}

// 添加tbody滚动相关样式
// .scrollable-tbody {
//   display: block;
//   max-height: 600px; // 根据需要调整高度
//   overflow-y: auto;
//   width: 100%;
// }

/* 表头行和内容行保持相同宽度 */
.market-table thead tr,
.market-table tbody tr {
  display: table;
  width: 100%;
  table-layout: fixed; /* 固定列宽布局 */
}

/* 修复滚动时最后一列边框问题 */
.market-table td:last-child {
  border-right: none;
}

.market-table th,
.market-table td {
  padding: 14px 12px;
  text-align: right;
  font-size: 14px;
}

.market-table th {
  font-weight: 600;
  color: #64748b;
  position: relative;
  user-select: none;
}

.market-table th:first-child,
.market-table td:first-child {
  text-align: left;
  padding-left: 20px;
}

.market-table th:nth-child(2),
.market-table td:nth-child(2) {
  text-align: left;
}

.market-table tbody tr {
  border-bottom: 1px solid #f1f5f9;
  transition: background-color 0.2s;
}

.market-table tbody tr:hover {
  background-color: #f8fafc;
}

.market-table tbody tr.odd {
  background-color: #f8fafc;
}

.coin-row {
  transition: all 0.2s ease;
}

.coin-row:hover {
  transform: translateX(4px);
}
/* 加载更多按钮样式 */
.load-more-btn {
  background-color: #fcbaa9;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s;
  margin: 20px auto;
  display: block;
}

.load-more-btn:hover {
  // background-color: #2563eb;
}

.load-more-btn:disabled {
  background-color: #94a3b8;
  cursor: not-allowed;
}
.coin-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.coin-logo {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.coin-details {
  text-align: left;
}

.coin-name {
  font-weight: 600;
  color: #0f172a;
  display: block;
}

.coin-symbol {
  font-size: 12px;
  color: #64748b;
  text-transform: uppercase;
}

.trend-column {
  padding: 8px 12px;
}

.trend-chart {
  display: inline-block;
  vertical-align: middle;
}

.up {
  color: #10b981;
}

.down {
  color: #ef4444;
}

/* 页脚 */
.page-footer {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;
  text-align: center;
  color: #64748b;
  font-size: 14px;
}

.page-footer p {
  margin: 5px 0;
}

/* 新增加载更多相关样式 */
.loading-more {
  text-align: center;
  padding: 20px 0;
}

.loading-more .loading-spinner {
  width: 32px;
  height: 32px;
  margin-bottom: 10px;
}

.no-more-data {
  text-align: center;
  padding: 20px 0;
  color: #64748b;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .market-table th:nth-child(6),
  .market-table td:nth-child(6),
  .market-table th:nth-child(7),
  .market-table td:nth-child(7) {
    display: none;
  }
}

@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr 1fr;
  }

  .market-table th:nth-child(3),
  .market-table td:nth-child(3),
  .market-table th:nth-child(5),
  .market-table td:nth-child(5) {
    display: none;
  }

  .market-table th,
  .market-table td {
    padding: 12px 8px;
    font-size: 13px;
  }

  .coin-logo {
    width: 28px;
    height: 28px;
  }
}

@media (max-width: 480px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }

  .container {
    padding: 15px 10px;
  }

  .page-header h1 {
    font-size: 24px;
  }

  .market-table th:nth-child(8),
  .market-table td:nth-child(8) {
    display: none;
  }

  .filters {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box {
    max-width: none;
  }
}

/* 排序相关样式 - 改为上下排列的按钮 */
.sortable-header {
  cursor: pointer;
  position: relative;
  padding-right: 28px; /* 调整右侧 padding 适配上下排列图标 */
  padding-top: 6px;
  padding-bottom: 6px;
}

.sort-indicator {
  position: absolute;
  /* right: 6px; */
  top: 50%;
  transform: translateY(-50%);
  width: 21px; /* 上下排列图标的宽度 */
  height: 30px; /* 上下排列图标的高度 */
  display: inline-block;
  transition: all 0.2s ease;
  background-repeat: no-repeat;
  background-position: center;
}

/* 未排序状态 - 显示上下箭头组合 */
.sort-indicator--none {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2394a3b8'%3E%3Cpath d='M7 14l5-5 5 5H7zm0-6v2h10V8H7z'/%3E%3C/svg%3E");
  opacity: 0.5;
}

/* 升序状态 - 显示向上箭头 */
.sort-indicator--asc {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%233b82f6'%3E%3Cpath d='M7 14l5-5 5 5H7z'/%3E%3C/svg%3E");
}

/* 降序状态 - 显示向下箭头 */
.sort-indicator--desc {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%233b82f6'%3E%3Cpath d='M7 10l5 5 5-5H7z'/%3E%3C/svg%3E");
}

.sortable-header:hover {
  background-color: rgba(0, 0, 0, 0.02);
}

.sortable-header:hover .sort-indicator--none {
  opacity: 1;
  transform: translateY(-50%) scale(1.1);
}
</style>
